package cn.bitkit.component.common;

import cn.bitkit.base.entity.FileViewInfo;
import cn.bitkit.tools.file.FileUtil;
import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class HttpFileHandler {

    public static ResponseEntity<AbstractResource> getEntity(FileViewInfo fileViewInfo){
        AbstractResource resource = getResource(fileViewInfo);
        if(resource == null){
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .header("message", "文件下载失败")
                    .build();
        }
        ContentDisposition.Builder builder = ContentDisposition.attachment();
        if(!fileViewInfo.getAttachment()){
            builder = ContentDisposition.inline();
        }
        if(fileViewInfo.getFileName() == null){
            fileViewInfo.setFileName("file");
        }

        MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
        if(fileViewInfo.getFile() != null){
            mediaType = MediaType.parseMediaType(FileUtil.getMediaType(fileViewInfo.getFile()));
        }
        String contentDisposition = builder
                .filename(URLEncoder.encode(fileViewInfo.getFileName(), StandardCharsets.UTF_8))
                .build().toString();
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                .contentType(mediaType)
                .body(resource);
    }

    public static AbstractResource getResource(FileViewInfo fileViewInfo){
        if(fileViewInfo.getInputStream() != null){
            return new InputStreamResource(fileViewInfo.getInputStream());
        }
        if(fileViewInfo.getBytes() != null){
            return new ByteArrayResource(fileViewInfo.getBytes());
        }
        if(fileViewInfo.getFile() != null){
            return new FileSystemResource(fileViewInfo.getFile());
        }
        return null;
    }

}
